package com.tronsis.distribution.fragment;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lzy.imagepicker.bean.ImageItem;
import com.tronsis.distribution.Constants;
import com.tronsis.distribution.R;
import com.tronsis.distribution.activity.training.ContactsActivity;
import com.tronsis.distribution.activity.training.CourseActivity;
import com.tronsis.distribution.activity.training.CourseDetailActivity;
import com.tronsis.distribution.bean.CourseBean;
import com.tronsis.distribution.bean.TeamTrainerBean;
import com.tronsis.distribution.biz.factory.TeamBizFactory;
import com.tronsis.distribution.http.Url;
import com.tronsis.distribution.util.CommonUtil;
import com.tronsis.library.adapter.recyclerview.CommonAdapter;
import com.tronsis.library.adapter.recyclerview.MultiItemTypeAdapter;
import com.tronsis.library.adapter.recyclerview.base.ViewHolder;
import com.tronsis.library.fragment.BaseFragment;
import com.tronsis.library.http.ListBean;
import com.tronsis.library.http.UICallBack;
import com.tronsis.library.imageloader.ImageLoader;
import com.tronsis.library.util.DateUtil;
import com.tronsis.library.util.DisplayUtil;
import com.tronsis.library.util.DownloadUtil;
import com.tronsis.library.util.EasyPermissions;
import com.tronsis.library.util.SRFConfigUtil;
import com.tronsis.library.util.StringUtil;
import com.tronsis.library.util.ToastUtil;
import com.tronsis.library.widget.CircleImageView;
import com.tronsis.library.widget.MyDecoration;
import com.tronsis.library.widget.RecycleViewDivider;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


public class TeamTrainFragment extends BaseFragment {
    @BindView(R.id.ll_contacts_more)
    LinearLayout mLlContactsMore;
    @BindView(R.id.rv_contacts)
    RecyclerView mRvContacts;
    @BindView(R.id.ll_course_more)
    LinearLayout mLlCourseMore;
    @BindView(R.id.rv_course)
    RecyclerView mRvCourse;
    @BindView(R.id.srl_training)
    SwipeRefreshLayout mSrl;
    @BindView(R.id.tv_course_count)
    TextView mTvCourseCount;


    private int mContactsPage = 1;
    private int mContactsSize = 2;

    private int mCoursePage = 1;
    private int mCourseSize = 2;


    private CommonAdapter<TeamTrainerBean> mContactsAdapter;
    private List<TeamTrainerBean> mContactsList = new ArrayList<>();

    private CommonAdapter<CourseBean> mCourseAdapter;
    private List<CourseBean> mCourseList = new ArrayList<>();

    @Override
    protected View onCreateView() {
        View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_team_train, null);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initData() {

        initContactsRv();
        initCourseRv();
        httpTrainer(mContactsPage, mContactsSize, true);
        httpMyCourse(mCoursePage, mCourseSize, true);
    }

    private void initContactsRv() {
        SRFConfigUtil.initSwipeRefreshLayout(mSrl);
        mSrl.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                httpTrainer(mContactsPage, mContactsSize, true);
                httpMyCourse(mCoursePage, mCourseSize, true);
            }
        });

        mContactsAdapter = new CommonAdapter<TeamTrainerBean>(mContext, mContactsList, R.layout.item_contacts) {
            @Override
            protected void convert(ViewHolder holder, final TeamTrainerBean teamTrainerBean, int position) {
                CircleImageView iv = holder.getView(R.id.iv_avatar);
                ImageLoader.displayAvatar(mContext, Url.FILE_DOWNLOAD + teamTrainerBean.getAvatarFid(), iv);
                holder.setText(R.id.tv_name, teamTrainerBean.getName());
                if (position == 0 && teamTrainerBean.getJob() == null) {
                    holder.setText(R.id.tv_job, "销售经理");
                } else {
                    holder.setText(R.id.tv_job, teamTrainerBean.getJob());
                }
                holder.setOnClickListener(R.id.bt_wechat, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        showDialog(teamTrainerBean.getWechatVcardFid());
                    }
                });

            }


        };

        int height = DisplayUtil.getInstance(mContext).dp2px(1);
        int color = Color.parseColor("#F4F4F4");
        RecycleViewDivider decoration = new RecycleViewDivider(mContext, MyDecoration.VERTICAL_LIST, height, color);
        mRvContacts.addItemDecoration(decoration);
        mRvContacts.setLayoutManager(new LinearLayoutManager(mContext));
        mRvContacts.setAdapter(mContactsAdapter);
    }

    private void initCourseRv() {

        mCourseAdapter = new CommonAdapter<CourseBean>(mContext, mCourseList, R.layout.item_course) {
            @Override
            protected void convert(ViewHolder holder, CourseBean courseBean, int position) {
                String url = "";
                ArrayList<ImageItem> list = CommonUtil.getSplitImage(courseBean.getImageFid());
                if (list.size() > 0) {
                    url = list.get(0).url;
                }
                holder.setImageByUrl(mContext, R.id.iv_cover, url);
                holder.setText(R.id.tv_name, getString(R.string.format_create_name, courseBean.getCreatorName()));
                holder.setText(R.id.tv_course, courseBean.getName());
                holder.setText(R.id.tv_createdOn, getString(R.string.format_time, DateUtil.getDateTimeString(courseBean.getCreatedOn())));
            }
        };

        mCourseAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Intent intent = new Intent(mContext, CourseDetailActivity.class);
                intent.putExtra("courseId", mCourseList.get(position).getCourseId());
                startActivity(intent);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        int height = DisplayUtil.getInstance(mContext).dp2px(1);
        int color = Color.parseColor("#F4F4F4");
        RecycleViewDivider decoration = new RecycleViewDivider(mContext, MyDecoration.VERTICAL_LIST, height, color);
        mRvCourse.addItemDecoration(decoration);
        mRvCourse.setLayoutManager(new LinearLayoutManager(mContext));
        mRvCourse.setAdapter(mCourseAdapter);
    }

    @OnClick(R.id.ll_contacts_more)
    void onContactsMoreClick() {
        Intent intent = new Intent(mContext, ContactsActivity.class);
        startActivity(intent);
    }

    @OnClick(R.id.ll_course_more)
    void onCourseMoreClick() {
        Intent intent = new Intent(mContext, CourseActivity.class);
        startActivity(intent);
    }

    private void showDialog(final String wechatVcardFid) {
        if (StringUtil.isBlank(wechatVcardFid)) {
            ToastUtil.showMessage(getContext(), "未找到微信二维码");
            return;
        }
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_add_wechat, null, false);
        final AlertDialog dialog = new AlertDialog.Builder(getContext()).setView(view).create();

        ImageView ivQrCode = view.findViewById(R.id.iv_qr_code);
        ImageLoader.display(getContext(), Url.FILE_DOWNLOAD + wechatVcardFid, ivQrCode);
        dialog.show();
        ImageButton btnClose = view.findViewById(R.id.mbt_close);
        btnClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        Button btnSave = view.findViewById(R.id.btn_save);
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (EasyPermissions.hasPermissions(mContext, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    dialog.dismiss();
                    httpDownload(wechatVcardFid);
                } else {
                    EasyPermissions.requestPermissions(mContext, getString(R.string.perm_tip), 0x111, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                }

            }
        });
    }

    private void httpDownload(final String id) {
        showLoadingDialog();
        DownloadUtil.get().download(Url.FILE_DOWNLOAD + id, Constants.SYSTEM_IMAGE_PATH, id + ".png", new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess() {
                Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissLoadingDialog();
                        ToastUtil.showMessage(mContext, "下载完成");
                        MediaScannerConnection.scanFile(mContext, new String[]{Constants.SYSTEM_IMAGE_PATH + File.separator + id + ".png"}, new String[]{"image/jpeg"}, new MediaScannerConnection.OnScanCompletedListener() {
                            @Override
                            public void onScanCompleted(String path, Uri uri) {
                                Log.d("scanFile", "onScanCompleted : " + path);
                            }
                        });
                    }
                });
            }


            @Override
            public void onDownloading(int progress) {

            }

            @Override
            public void onDownloadFailed() {
                Objects.requireNonNull(getActivity()).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissLoadingDialog();
                        ToastUtil.showMessage(mContext, "下载失败");
                    }
                });
            }
        });

    }

    private void httpTrainer(int page, int size, final boolean isRefresh) {
        try {

            TeamBizFactory.createBiz().listMyTrainer(getActivity(), page, size, new UICallBack() {
                @Override
                public void onStart() {
                    mSrl.setRefreshing(true);
                }

                @Override
                public void onRefresh(Object data) {
                    mSrl.setRefreshing(false);
                    ListBean listBean = (ListBean) data;
                    List<TeamTrainerBean> list = listBean.getList();
                    if (isRefresh) {
                        mContactsList.clear();
                        mContactsList.addAll(list);
                    }
                    mContactsAdapter.notifyDataSetChanged();

                }

                @Override
                public void onFailure(int status) {
                    mSrl.setRefreshing(false);

                }
            });

        } catch (Exception e) {
            mSrl.setRefreshing(false);
            e.printStackTrace();
        }
    }

    private void httpMyCourse(int page, int size, final boolean isRefresh) {
        try {

            TeamBizFactory.createBiz().listMyCourse(getActivity(), page, size, null, new UICallBack() {
                @Override
                public void onStart() {
                    mSrl.setRefreshing(true);
                }

                @Override
                public void onRefresh(Object data) {
                    mSrl.setRefreshing(false);
                    ListBean listBean = (ListBean) data;
                    mTvCourseCount.setText(getString(R.string.format_my_course, listBean.getTotal()));
                    List<CourseBean> list = listBean.getList();
                    if (isRefresh) {
                        mCourseList.clear();
                        mCourseList.addAll(list);
                    } else {
                        mCourseList.addAll(list);
                    }
                    mCourseAdapter.notifyDataSetChanged();

                }

                @Override
                public void onFailure(int status) {
                    mSrl.setRefreshing(false);
                }
            });

        } catch (Exception e) {
            mSrl.setRefreshing(false);
            e.printStackTrace();
        }
    }


}
